import { Modal, Table } from "antd";
import type { ProTableColumns } from "../Index";
import { useState, useEffect } from "react";
interface DataType {
	name: string;
	id: string;
}
export const CustomColumns = ({
	showSelectCustom,
	setShowSelectCustom,
	columns,
	changeColumns,
}: {
	showSelectCustom: boolean;
	setShowSelectCustom: (showSelectCustom: boolean) => void;
	columns: ProTableColumns<any>;
	changeColumns: (columns: React.Key[]) => void;
}) => {
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);

	// 数据源
	const dataSource: any[] =
		columns?.map((item) => {
			return {
				name: item.title,
				id: item.key,
			};
		}) || [];

	// 默认选中的列
	const defaultSelectedRowKeys = columns?.map((item) => {
		return item.key;
	});

	// 设置默认选中的列
	useEffect(() => {
		setSelectedRowKeys(defaultSelectedRowKeys as React.Key[]);
	}, []);

	// 自定义列
	const column: ProTableColumns<DataType> = [
		{
			title: "列名",
			dataIndex: "name",
			key: "name",
		},
	];

	// 选中行
	const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
		setSelectedRowKeys(newSelectedRowKeys);
	};
	const rowSelection = {
		selectedRowKeys,
		onChange: onSelectChange,
	};

	// 确定
	const onOk = () => {
		setShowSelectCustom(false);
		changeColumns(selectedRowKeys);
	};

	return (
		<div>
			<Modal
				title="自定义列"
				open={showSelectCustom}
				onOk={onOk}
				zIndex={100000}
				onCancel={() => {
					setShowSelectCustom(false);
				}}
			>
				<Table<DataType>
					columns={column}
					dataSource={dataSource}
					style={{ marginTop: 24 }}
					pagination={false}
					rowKey={(record) => record.id}
					rowSelection={rowSelection}
					bordered
				/>
			</Modal>
		</div>
	);
};
